<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 7/12/17
 * Time: 10:13 AM
 */
declare(strict_types=1);


namespace application\service\library;

use Workerman\Connection\TcpConnection;
use Workerman\Worker;
use wshore\library\Service;

class VMStatWorker extends Service
{

    public function start()
    {
        $worker = new Worker('Websocket://0.0.0.0:' . $this->port);
        $worker->name = 'VMStatWorker';
// 进程启动时，开启一个vmstat进程，并广播vmstat进程的输出给所有浏览器客户端
        $worker->onWorkerStart = function ($worker) {
            // 把进程句柄存储起来，在进程关闭的时候关闭句柄
            $worker->process_handle = popen('vmstat 1', 'r');
            if ($worker->process_handle) {
                $process_connection = new TcpConnection($worker->process_handle);
                $process_connection->onMessage = function ($process_connection, $data) use ($worker) {
                    foreach ($worker->connections as $connection) {
                        if (is_string($data) and strpos($data, 'procs') === 0) {
                            continue;
                        }
                        $connection->send($data);
                    }
                };
            } else {
                echo "vmstat 1 fail\n";
            }
        };

        // 进程关闭时
        $worker->onWorkerStop = function ($worker) {
            @shell_exec('killall vmstat');
            @pclose($worker->process_handle);
        };

        parent::start(); // TODO: Change the autogenerated stub
    }

}